package com.jk.aop;


import com.jk.annotation.MyLog;
import com.jk.dao.LogRepository;
import com.jk.entily.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;


@Aspect   //切面
@Component
public class MyLogAspect {

    @Autowired
    private LogRepository logRepository;

    private ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Pointcut("@annotation(com.jk.annotation.MyLog)")
    public void logPointcut() {
    }

    @Before("@annotation(myLog)")
    public void doBefore(MyLog myLog) {
        //记录接口的开始时
        startTime.set(System.currentTimeMillis());

    }

    @AfterReturning(pointcut = "logPointcut()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        // 获取方法参数、方法名、返回结果等信息
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();
        String params = Arrays.toString(joinPoint.getArgs());
        String returnValue = (result != null) ? result.toString() : "void";

        // 获取请求 URL 和方法执行时间
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        long duration = System.currentTimeMillis()- startTime.get();

        // 构造日志对象并保存到数据库
        Log log = new Log();
        log.setMethodName(methodName);
        log.setClassName(className);
        log.setParams(params);
        log.setReturnValue(returnValue);
        log.setUrl(url);
        log.setDuration(duration);
        log.setCreateTime(new Date());
        logRepository.save(log);
    }
}